class Node:
    def __init__(self, *args, **kwargs):
        self.data = None
        self.next = None

    # node += N (N is a integer number)
    def __iadd__(self, other):
        node_ptr = self
        assert isinstance(other, int)
        while other:
            node_ptr = node_ptr.next
            other -= 1
        return node_ptr


# 琏表迭代器
class LinkIterator:
    def __init__(self, head):
        self._link_ptr = head.next

    def __next__(self):
        if self._link_ptr is None:
            raise StopIteration

        data = self._link_ptr.data
        self._link_ptr += 1
        return data


class Link:
    def __init__(self, *args, **kwargs):
        self.head = Node()
        self.count = 0

    # 根据位置找到对应的节点（pos从0开始）
    def __get_node_by_pos(self, pos):
        node_ptr = self.head
        node_ptr += pos
        return node_ptr

    def append(self, data):
        self.insert(self.count, data)

    def insert(self, pos, data):
        node_ptr = self.__get_node_by_pos(pos)

        next_node = node_ptr.next
        node = Node()
        node.data = data
        node.next = next_node
        node_ptr.next = node
        self.count += 1

    def index(self, data):
        node_ptr = self.head.next
        index = 0
        while node_ptr:
            if node_ptr.data == data:
                return index
            index += 1
            node_ptr += 1

        raise ValueError("{} is not in link".format(data))

    def __iter__(self):
        return LinkIterator(self.head)

    def __setitem__(self, key, value):
        self.insert(key, value)

    def __getitem__(self, item):
        node = self.__get_node_by_pos(item + 1)
        return node.data

    def __len__(self):
        return self.count

    def remove(self, data):
        node_ptr = self.head
        index = self.index(data)

        while index:
            node_ptr += 1
            index -= 1

        next_node = node_ptr.next.next
        node_ptr.next = next_node
        self.count -= 1


l = Link()
l.append(1)
l.append("hello")
l.append(4)
l.insert(0, 5)
l[3] = 6
# x = LinkIterator(l.head)

# print(l.index(8))

l.remove(6)
l.remove(5)
for x in l:
    print(x)

print(l[2])

# print("there are {} numbers".format(len(l)))
